package com.mycommune.servlet;

import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.xmpp.JID;
import com.google.appengine.api.xmpp.MessageBuilder;
import com.google.appengine.api.xmpp.SendResponse;
import com.google.appengine.api.xmpp.XMPPService;
import com.google.appengine.api.xmpp.XMPPServiceFactory;
import com.mycommune.service.MyCommuneService;
import com.mycommune.service.MyCommuneServiceImpl;
import com.mycommune.servlet.ChatSessionFactory.ChatSession;

public class XMPPReceiverServlet extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public void doPost(HttpServletRequest req, HttpServletResponse res)
			throws IOException {
		XMPPService xmpp = XMPPServiceFactory.getXMPPService();
		com.google.appengine.api.xmpp.Message message = xmpp.parseMessage(req);

		JID fromJid = message.getFromJid();
		String body = message.getBody();
		StringBuilder reply = new StringBuilder();
		String sessionKey = fromJid.getId();
		
		try {
			MyCommuneService communeService = new MyCommuneServiceImpl();
			reply.append(communeService.getTabHeaders());
			com.google.appengine.api.xmpp.Message msg = new MessageBuilder()
					.withRecipientJids(fromJid).withBody(reply.toString())
					.build();
			boolean messageSent = false;
			if (xmpp.getPresence(fromJid).isAvailable()) {
				SendResponse status = xmpp.sendMessage(msg);
				messageSent = (status.getStatusMap().get(fromJid) == SendResponse.Status.SUCCESS);
			}
		} catch (Exception e) {
			reply.append(e);
			com.google.appengine.api.xmpp.Message msg = new MessageBuilder()
					.withRecipientJids(fromJid).withBody(reply.toString())
					.build();
			boolean messageSent = false;
			if (xmpp.getPresence(fromJid).isAvailable()) {
				SendResponse status = xmpp.sendMessage(msg);
				messageSent = (status.getStatusMap().get(fromJid) == SendResponse.Status.SUCCESS);
			}
		}
	}
}
